<!DOCTYPE html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script>let additionalChromiumResources = ["resources/xr-internal-device-mocking.js"];</script>
<script src="/webxr/resources/webxr_util.js"></script>
<script src="/webxr/resources/webxr_test_constants.js"></script>

<script>
// This test manipulates mojo directly to simulate some behavior, and as such is
// chromium specific.
const testName = "Outstanding promises get rejected if environmentProvider disconnects";

const fakeDeviceInitParams = { supportedModes: ["immersive-ar"],
                             views: VALID_VIEWS,
                             supportsEnvironmentIntegration: true,
                             supportedFeatures: ALL_FEATURES };

let refSpace = undefined;

const testFunction = function(session, fakeDeviceController, t) {
  // Override some promise-based method from mock runtime so that we can
  // also return a promise that never resolves or rejects.
  // This is so that we can simulate a disconnect while the mojo call is still
  // outstanding.
  let immediatelyResolvePromise = true;
  MockRuntime.prototype.subscribeToHitTest = function(nativeOriginInformation, entityTypes, ray) {
    if (!immediatelyResolvePromise) {
      return new Promise((resolve,reject) => { });
    }

    return Promise.resolve({
      result : SubscribeToHitTestResult.SUCCESS,
      subscriptionId : 1001
    });
  }

  return session.requestReferenceSpace('local')
    .then((referenceSpace) => {
      refSpace = referenceSpace;

      // Request a first hit test to ensure that all of the mojo connections are
      // up and running.
      return session.requestHitTestSource({"space" :refSpace});
    })
    .then(() => {
      immediatelyResolveHitTest = false;
      const hitTestSourcePromise = session.requestHitTestSource({"space" :refSpace})
      fakeDeviceController.closeEnvironmentIntegrationProvider();
      return hitTestSourcePromise;
    })
    .then(() => {
        assert_unreached("Promise should not resolve");
      },
      (err) => {
        assert_equals(err.name, "InvalidStateError");
      });
};

xr_session_promise_test(
  testName, testFunction, fakeDeviceInitParams, 'immersive-ar', {requiredFeatures: ["hit-test"]});

</script>
